package com.t18;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;

/**
 * Created by xuyiwei on 2018/9/2.
 */
public class TextFile extends ArrayList<String> {
    public static String read(String fileName){
        StringBuilder sb = new StringBuilder();
        try{
            BufferedReader in = new BufferedReader(
                    new FileReader(
                            new File(fileName).getCanonicalFile()
                    )
            );
            String s;
            try {
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    sb.append("\n");
                }
            }finally {
                in.close();
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return sb.toString();
    }
    public static void write(String fileName,String text){
        try{
            PrintWriter pw = new PrintWriter(new File(fileName).getCanonicalFile());
            try{
                pw.println(text);
            }finally {
                pw.close();
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    public TextFile(String fileName,String splitter){
        super(Arrays.asList(read(fileName).split(splitter)));
        if(get(0).equals(""))remove(0);
    }
    public TextFile(String fileName){
        this(fileName,"\n");
    }
    public void write(String fileName){
        try{
            PrintWriter pw = new PrintWriter(new File(fileName).getCanonicalFile());
            try{
                for(String item:this){
                    pw.println(item);
                }
            }finally {
                pw.close();
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String file = read("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile.java");
        write("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile.txt",file);
        TextFile text = new TextFile("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile.txt");
        text.write("/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile2.txt");
        TreeSet<String> words = new TreeSet<String>(new TextFile(
                "/Users/xuyiwei/Documents/javaBase/jdk/src/com/t18/TextFile2.txt","\\W+"
        ));
        System.out.println(words.headSet("a"));
    }
}
